package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import com.tanhua.model.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    //上报地理位置
    @Override
    public void addLocation(Double latitude, Double longitude, String address, Long userId) {
        long millis = System.currentTimeMillis();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        if (mongoTemplate.exists(query, UserLocation.class)) {
            Update update = new Update();
            update.set("lastUpdated",millis);
            update.set("updated",millis);
            update.set("location",new GeoJsonPoint(latitude, longitude));
            //update.set("address",address);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }else{
            UserLocation location = new UserLocation();
            location.setAddress(address);
            location.setId(ObjectId.get());
            location.setUserId(userId);
            location.setCreated(millis);
            location.setLastUpdated(millis);
            location.setUpdated(millis);
            location.setLocation(new GeoJsonPoint(latitude,longitude));
            mongoTemplate.save(location);
        }
    }

    //搜附近
    @Override
    public List<UserLocationVo> searchNear(Long userId, Long miles) {
        //1、根据用户id，查询当前用户的位置
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        //2、指定查询的半径范围
        GeoJsonPoint location = userLocation.getLocation();
        Distance distance = new Distance(miles/1000, Metrics.KILOMETERS);
        //3、根据此半径画圆
        Circle circle = new Circle(location,distance); //圆点，半径
        //4、调用mongotemplate查询 List<UserLocation>
        Query nearQuery = new Query(
                Criteria.where("location").withinSphere(circle)
        );
        List<UserLocation> userLocations = mongoTemplate.find(nearQuery, UserLocation.class);
        //5、转化为List<UserLocationVo>
        return UserLocationVo.formatToList(userLocations);
    }

    //查询地理位置
    @Override
    public GeoJsonPoint findLocation(Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        return userLocation.getLocation();
    }

    //更新地理位置
    @Override
    public Boolean updateLocation(Long userId, Double longitude, Double latitude, String address) {
        try {
            //1、根据用户id查询位置信息
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
            if(location == null) {
                //2、如果不存在用户位置信息，保存
                location = new UserLocation();
                location.setUserId(userId);
                location.setAddress(address);
                location.setCreated(System.currentTimeMillis());
                location.setUpdated(System.currentTimeMillis());
                location.setLastUpdated(System.currentTimeMillis());
                location.setLocation(new GeoJsonPoint(longitude,latitude));
                mongoTemplate.save(location);
            }else {
                //3、如果存在，更新
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated", location.getUpdated());
                mongoTemplate.updateFirst(query,update,UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //查询附近的用户（返回的是附近的人的所有用户id，包含当前用户的id）
    @Override
    public List<Long> queryNearUser(Long userId, Double metre) {
        //1、根据用户id，查询用户的位置信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if(location == null) {
            return null;
        }
        //2、已当前用户位置绘制原点
        GeoJsonPoint point = location.getLocation();
        //3、绘制半径
        Distance distance = new Distance(metre / 1000, Metrics.KILOMETERS);
        //4、绘制圆形
        Circle circle = new Circle(point, distance);
        //5、查询
        Query locationQuery = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> list = mongoTemplate.find(locationQuery, UserLocation.class);
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }

}
